package com.alibaba.pet.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.pet.domain.PetType;
import com.alibaba.pet.service.IPetTypeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-03-13
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Override
    public List<PetType> tree() {
        List<PetType> result = new ArrayList<>();
        List<PetType> all = super.findAll();
        Map<Long, PetType> collect = all.stream().collect(Collectors.toMap(PetType::getId, e -> e));
        for(PetType petType : all){
            if (petType != null && null == petType.getPid()){
                result.add(petType);
            } else {
                PetType parent = collect.get(petType.getPid());
                parent.getChildren().add(petType);
            }
        }
        return result;
    }
}
